package org.sakai.service;

import org.sakai.mapper.DiseaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DiseaseService {

    @Autowired
    private DiseaseMapper diseaseMapper;

    /**
     * 获取疾病列表（分页）
     */
    public Map<String, Object> getDiseaseList(int pageNum, int pageSize, String keyword, String isSpecialZone, Long departmentId, String sortBy, String sortOrder) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 添加调试日志
            System.out.println("疾病列表查询参数 - pageNum: " + pageNum + ", pageSize: " + pageSize + 
                             ", keyword: " + keyword + ", isSpecialZone: " + isSpecialZone + 
                             ", departmentId: " + departmentId + ", sortBy: " + sortBy + ", sortOrder: " + sortOrder);
            
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;
            
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("offset", offset);
            params.put("pageSize", pageSize);
            params.put("keyword", keyword);
            params.put("isSpecialZone", isSpecialZone);
            params.put("departmentId", departmentId);
            params.put("sortBy", sortBy);
            params.put("sortOrder", sortOrder);
            
            // 获取疾病列表
            List<Map<String, Object>> diseases = diseaseMapper.getDiseaseList(params);
            
            // 处理departments_json字段，转换为departments数组
            if (diseases != null) {
                for (Map<String, Object> disease : diseases) {
                    String departmentsJson = (String) disease.get("departments_json");
                    if (departmentsJson != null && !departmentsJson.isEmpty()) {
                        // 简单解析JSON字符串为部门信息
                        // 这里可以使用更复杂的JSON解析，暂时使用简单的字符串处理
                        disease.put("departments", parseDepartmentsJson(departmentsJson));
                    } else {
                        disease.put("departments", new ArrayList<>());
                    }
                    // 移除临时字段
                    disease.remove("departments_json");
                }
            }
            
            // 添加调试日志
            System.out.println("查询到的疾病数量: " + (diseases != null ? diseases.size() : 0));
            
            // 获取总数
            int total = diseaseMapper.getDiseaseCount(params);
            
            result.put("data", diseases);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("success", true);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取疾病列表失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取疾病详情
     */
    public Map<String, Object> getDiseaseDetail(Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> disease = diseaseMapper.getDiseaseById(id);
            
            if (disease != null) {
                // 获取疾病关联的科室信息
                List<Map<String, Object>> departments = diseaseMapper.getDepartmentsByDiseaseId(id);
                disease.put("departments", departments);
                
                result.put("data", disease);
                result.put("success", true);
            } else {
                result.put("success", false);
                result.put("message", "疾病信息不存在");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取疾病详情失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 搜索疾病
     */
    public Map<String, Object> searchDisease(String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, Object>> diseases = diseaseMapper.searchDisease(keyword);
            
            result.put("data", diseases);
            result.put("success", true);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "搜索疾病失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 解析部门JSON字符串
     */
    private List<Map<String, Object>> parseDepartmentsJson(String departmentsJson) {
        List<Map<String, Object>> departments = new ArrayList<>();
        
        try {
            if (departmentsJson != null && !departmentsJson.isEmpty()) {
                // 分割多个部门信息
                String[] deptArray = departmentsJson.split(",");
                for (String deptStr : deptArray) {
                    if (deptStr.contains("\"id\":") && deptStr.contains("\"name\":")) {
                        Map<String, Object> dept = new HashMap<>();
                        
                        // 提取ID
                        String idPart = deptStr.substring(deptStr.indexOf("\"id\":") + 5);
                        String id = idPart.substring(0, idPart.indexOf(",")).trim();
                        
                        // 提取name
                        String namePart = deptStr.substring(deptStr.indexOf("\"name\":\"") + 8);
                        String name = namePart.substring(0, namePart.lastIndexOf("\"")).trim();
                        
                        dept.put("id", Integer.parseInt(id));
                        dept.put("name", name);
                        departments.add(dept);
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("解析部门JSON失败: " + e.getMessage());
        }
        
        return departments;
    }
}
